package net.sashag.nadlandroid;

import java.util.Date;

import com.googlecode.androidannotations.annotations.Background;
import com.googlecode.androidannotations.annotations.EReceiver;
import com.googlecode.androidannotations.annotations.SystemService;
import com.parse.ParseException;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.util.Log;

@EReceiver
public class ProximityAlertReceiver extends BroadcastReceiver {

	@SystemService
	protected NotificationManager notificationManager;
	
	private static int notificationId; //Increasing, while the application is alive this will ensure we get fresh notifications
	
	@Override
	public void onReceive(Context context, Intent intent) {
		boolean entering = intent.getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING, false);
		if (!entering)
			return; //This is not interesting

		String apartmentId = intent.getStringExtra("ApartmentId");
		//The user has entered the vicinity of this apartment, post a notification
		//that will open the ApartmentDetailsActivity with that apartment.
		postNotification(context, apartmentId);
	}

	@Background
	protected void postNotification(Context context, String apartmentId) {
		Apartment apartment;
		try {
			apartment = Apartment.fromId(apartmentId);
		} catch (ParseException e) {
			Log.w("ProximityAlertReceiver", "Error retrieving apartment details: " + e.getMessage());
			return;
		}
		Notification notification = new Notification(
				R.drawable.nearapartmentnotification,
				"You are now near one of your favorite apartments",
				new Date().getTime());
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		Intent activityLaunch = new ApartmentDetailsActivity_.IntentBuilder_(context).apartment(apartment).get();
		activityLaunch.setFlags(activityLaunch.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
		PendingIntent contentIntent = PendingIntent.getActivity(context, -1, activityLaunch, PendingIntent.FLAG_UPDATE_CURRENT);
		notification.setLatestEventInfo(context,
				"Near Favorite Apartment",
				"You are now near the apartment on " + apartment.getAddress(),
				contentIntent);
		notificationManager.notify(++notificationId, notification);
	}

}
